package register

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

type Consul struct {
	Host string
	Port int
}

type RegistryClient interface {
	Register(host string, port int, name string, tags []string, id string) error
	DeRegister(serviceId string) error
}

func NewConsul(host string, port int) RegistryClient {
	return &Consul{
		Host: host,
		Port: port,
	}
}

func (c *Consul) Register(host string, port int, name string, tags []string, id string) error {
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", c.Host, c.Port)
	client, err := api.NewClient(cfg)
	if err != nil {
		zap.S().Fatalf("consul连接失败:", err.Error())
	}

	//生成对应的检查对象
	check := &api.AgentServiceCheck{
		HTTP:                             fmt.Sprintf("http://%s:%d/health", host, port),
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "15s",
	}

	err = client.Agent().ServiceRegister(&api.AgentServiceRegistration{
		ID:      id,
		Name:    name,
		Tags:    tags,
		Port:    port,
		Address: host,
		Check:   check,
	})
	if err != nil {
		zap.S().Fatalf("consul注册grpc失败:", err.Error())
	}

	return nil
}

func (c *Consul) DeRegister(serviceId string) error {
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", c.Host, c.Port)

	client, err := api.NewClient(cfg)
	if err != nil {
		zap.S().Fatalf("consul注销失败:", err.Error())
	}
	err = client.Agent().ServiceDeregister(serviceId)
	return err
}
